import { useState, useEffect } from "react";
import axios from "axios";
import { message } from "antd";

function usePublish(type) {
  const [dataSource, setDataSource] = useState();

  const fetchDate = async () => {
    const { username } = JSON.parse(localStorage.getItem("user"));
    const { data } = await axios.get(
      `/news?author=${username}&publishState=${type}&_expand=category`
    );
    console.log(data);
    setDataSource(data);
  };

  useEffect(() => {
    fetchDate();
  }, []);

  const handlePublish = async (id) => {
    console.log(id);
    const res = await axios.patch(`/news/${id}`, {
      publishState: 2,
      publishTime: Date.now(),
    });
    if (res.status === 200) {
      fetchDate();
      message.success("发布成功");
    }
  };
  const handleSunset = async (id) => {
    console.log(id);
    const res = await axios.patch(`/news/${id}`, {
      publishState: 3,
      publishTime: Date.now(),
    });
    if (res.status === 200) {
      fetchDate();
      message.success("下线成功");
    }
  };
  const handleDelete = async (id) => {
    console.log(id);
    const res = await axios.delete(`/news/${id}`, {
      publishState: 3,
      publishTime: Date.now(),
    });
    if (res.status === 200) {
      fetchDate();
      message.success("删除成功");
    }
  };

  return {
    dataSource,
    handlePublish,
    handleSunset,
    handleDelete,
  };
}

export default usePublish;
